#!/usr/bin/env python3
"""
深度分析Ford Focus页面
专门寻找车型详细信息和"See Full Specification"按钮
"""

import sys
import os
import json
import time
from datetime import datetime

sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from src.base import BaseWebDriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException
from selenium.webdriver.common.action_chains import ActionChains

class FocusDeepAnalyzer:
    """Ford Focus深度分析器"""
    
    def __init__(self):
        self.driver_manager = BaseWebDriver()
        self.driver = None
        self.wait = None
        self.results = {
            "analysis_date": datetime.now().isoformat(),
            "target_url": "",
            "models_detailed": [],
            "specification_buttons": [],
            "interactive_elements": [],
            "network_apis": [],
            "page_structure": {},
            "errors": []
        }
    
    def setup_and_navigate(self):
        """初始化并导航到页面"""
        try:
            # 初始化WebDriver
            self.driver_manager.setup_driver()
            self.driver = self.driver_manager.driver
            self.wait = WebDriverWait(self.driver, 15)
            
            # 加载URL
            with open('fetchNgc2.json', 'r', encoding='utf-8') as f:
                config = json.load(f)
            url0 = config['sub_model']['url0']
            
            print(f"🌐 正在访问: {url0}")
            self.results["target_url"] = url0
            
            self.driver.get(url0)
            time.sleep(5)
            
            # 处理Cookie
            self.handle_cookies()
            
            print(f"✅ 页面加载成功: {self.driver.title}")
            return True
            
        except Exception as e:
            error_msg = f"初始化失败: {e}"
            print(f"❌ {error_msg}")
            self.results["errors"].append(error_msg)
            return False
    
    def handle_cookies(self):
        """处理Cookie弹窗"""
        try:
            cookie_selectors = [
                "#onetrust-accept-btn-handler",
                "button[id*='accept']",
                "button[class*='accept']",
                ".ot-accept-all-handler"
            ]
            
            for selector in cookie_selectors:
                try:
                    elements = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    for element in elements:
                        if element.is_displayed():
                            self.driver.execute_script("arguments[0].click();", element)
                            print(f"✅ 处理了Cookie弹窗")
                            time.sleep(2)
                            return
                except:
                    continue
                    
        except Exception as e:
            print(f"⚠️ Cookie处理异常: {e}")
    
    def scroll_and_analyze(self):
        """滚动页面并逐步分析"""
        try:
            print("\n🔍 开始深度页面分析...")
            
            # 逐步滚动页面
            scroll_positions = [0, 500, 1000, 1500, 2000, 2500, 3000]
            
            for i, scroll_pos in enumerate(scroll_positions):
                print(f"  📜 滚动到位置: {scroll_pos}px")
                self.driver.execute_script(f"window.scrollTo(0, {scroll_pos});")
                time.sleep(2)
                
                # 在每个位置分析页面内容
                self.analyze_current_view(f"position_{i}")
            
            # 回到顶部
            self.driver.execute_script("window.scrollTo(0, 0);")
            time.sleep(2)
            
        except Exception as e:
            error_msg = f"滚动分析失败: {e}"
            print(f"❌ {error_msg}")
            self.results["errors"].append(error_msg)
    
    def analyze_current_view(self, position_id):
        """分析当前视图中的内容"""
        try:
            # 查找Focus相关的车型
            focus_selectors = [
                "h1:contains('Focus')",
                "h2:contains('Focus')",
                "h3:contains('Focus')",
                "div:contains('Focus')",
                "[data-testid*='focus']",
                "[class*='focus']",
                ".model-name",
                ".variant-name",
                ".trim-level"
            ]
            
            models_in_view = []
            
            for selector in focus_selectors:
                try:
                    if 'contains(' in selector:
                        tag = selector.split(':')[0]
                        xpath = f"//{tag}[contains(text(), 'Focus')]"
                        elements = self.driver.find_elements(By.XPATH, xpath)
                    else:
                        elements = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    
                    for element in elements:
                        if element.is_displayed():
                            text = element.text.strip()
                            if 'focus' in text.lower() and len(text) > 5:
                                model_info = {
                                    "position": position_id,
                                    "selector": selector,
                                    "text": text[:150],
                                    "tag": element.tag_name,
                                    "location": {
                                        "x": element.location.get('x', 0),
                                        "y": element.location.get('y', 0)
                                    }
                                }
                                models_in_view.append(model_info)
                                
                except Exception as e:
                    continue
            
            # 查找按钮和交互元素
            button_selectors = [
                "button",
                "a[class*='button']",
                "a[class*='btn']",
                "[role='button']",
                ".cta",
                ".call-to-action"
            ]
            
            buttons_in_view = []
            
            for selector in button_selectors:
                try:
                    elements = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    for element in elements:
                        if element.is_displayed():
                            text = element.text.strip()
                            href = element.get_attribute('href')
                            onclick = element.get_attribute('onclick')
                            
                            # 特别关注包含specification, spec, detail等关键词的按钮
                            keywords = ['specification', 'spec', 'detail', 'learn more', 'view', 'see', 'full']
                            
                            if any(keyword in text.lower() for keyword in keywords) and text:
                                button_info = {
                                    "position": position_id,
                                    "selector": selector,
                                    "text": text[:100],
                                    "href": href,
                                    "onclick": onclick,
                                    "tag": element.tag_name,
                                    "class": element.get_attribute('class'),
                                    "location": {
                                        "x": element.location.get('x', 0),
                                        "y": element.location.get('y', 0)
                                    }
                                }
                                buttons_in_view.append(button_info)
                                
                except Exception as e:
                    continue
            
            # 记录结果
            if models_in_view:
                self.results["models_detailed"].extend(models_in_view)
                print(f"    🚗 在 {position_id} 发现 {len(models_in_view)} 个车型元素")
            
            if buttons_in_view:
                self.results["interactive_elements"].extend(buttons_in_view)
                print(f"    🔘 在 {position_id} 发现 {len(buttons_in_view)} 个相关按钮")
                
        except Exception as e:
            print(f"    ❌ 分析 {position_id} 失败: {e}")
    
    def find_specification_buttons(self):
        """专门寻找规格说明按钮"""
        try:
            print("\n🔍 专门寻找 'See Full Specification' 按钮...")
            
            # 多种可能的文本变体
            spec_texts = [
                'See Full Specification',
                'Full Specification',
                'View Specification',
                'Specification',
                'See Specs',
                'View Specs',
                'Full Specs',
                'Technical Specs',
                'Vehicle Specs'
            ]
            
            spec_buttons = []
            
            for text in spec_texts:
                try:
                    # 使用XPath查找包含特定文本的元素
                    xpath = f"//*[contains(text(), '{text}')]"
                    elements = self.driver.find_elements(By.XPATH, xpath)
                    
                    if elements:
                        print(f"  ✅ 找到包含 '{text}' 的元素: {len(elements)} 个")
                        
                        for element in elements:
                            try:
                                spec_info = {
                                    "search_text": text,
                                    "actual_text": element.text.strip(),
                                    "tag": element.tag_name,
                                    "href": element.get_attribute('href'),
                                    "onclick": element.get_attribute('onclick'),
                                    "class": element.get_attribute('class'),
                                    "id": element.get_attribute('id'),
                                    "is_displayed": element.is_displayed(),
                                    "is_enabled": element.is_enabled(),
                                    "location": element.location
                                }
                                spec_buttons.append(spec_info)
                                
                            except Exception as e:
                                print(f"    ❌ 分析元素失败: {e}")
                
                except Exception as e:
                    print(f"  ❌ 搜索 '{text}' 失败: {e}")
                    continue
            
            self.results["specification_buttons"] = spec_buttons
            print(f"✅ 总共找到 {len(spec_buttons)} 个规格相关按钮")
            
        except Exception as e:
            error_msg = f"寻找规格按钮失败: {e}"
            print(f"❌ {error_msg}")
            self.results["errors"].append(error_msg)
    
    def analyze_page_structure(self):
        """分析页面整体结构"""
        try:
            print("\n📋 分析页面结构...")
            
            structure = {
                "total_divs": len(self.driver.find_elements(By.TAG_NAME, "div")),
                "total_buttons": len(self.driver.find_elements(By.TAG_NAME, "button")),
                "total_links": len(self.driver.find_elements(By.TAG_NAME, "a")),
                "total_images": len(self.driver.find_elements(By.TAG_NAME, "img")),
                "total_scripts": len(self.driver.find_elements(By.TAG_NAME, "script")),
                "focus_mentions": 0,
                "price_elements": 0,
                "cta_elements": 0
            }
            
            # 统计Focus提及次数
            page_text = self.driver.find_element(By.TAG_NAME, "body").text.lower()
            structure["focus_mentions"] = page_text.count('focus')
            
            # 统计价格元素
            price_selectors = ["[class*='price']", "[id*='price']", "span:contains('£')"]
            for selector in price_selectors:
                try:
                    if 'contains(' in selector:
                        elements = self.driver.find_elements(By.XPATH, "//span[contains(text(), '£')]")
                    else:
                        elements = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    structure["price_elements"] += len(elements)
                except:
                    continue
            
            # 统计CTA元素
            cta_selectors = [".cta", ".call-to-action", "[class*='button']", "[role='button']"]
            for selector in cta_selectors:
                try:
                    elements = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    structure["cta_elements"] += len(elements)
                except:
                    continue
            
            self.results["page_structure"] = structure
            
            print(f"  📊 页面统计:")
            print(f"    - DIV元素: {structure['total_divs']}")
            print(f"    - 按钮: {structure['total_buttons']}")
            print(f"    - 链接: {structure['total_links']}")
            print(f"    - Focus提及: {structure['focus_mentions']} 次")
            print(f"    - 价格元素: {structure['price_elements']}")
            print(f"    - CTA元素: {structure['cta_elements']}")
            
        except Exception as e:
            error_msg = f"页面结构分析失败: {e}"
            print(f"❌ {error_msg}")
            self.results["errors"].append(error_msg)
    
    def save_results(self):
        """保存详细分析结果"""
        try:
            output_file = "./release/focus_deep_analysis.json"
            os.makedirs(os.path.dirname(output_file), exist_ok=True)
            
            with open(output_file, 'w', encoding='utf-8') as f:
                json.dump(self.results, f, ensure_ascii=False, indent=2)
            
            print(f"💾 详细分析结果已保存到: {output_file}")
            
        except Exception as e:
            print(f"❌ 保存结果失败: {e}")
    
    def cleanup(self):
        """清理资源"""
        try:
            if self.driver:
                self.driver_manager.cleanup()
        except Exception as e:
            print(f"⚠️ 清理资源时出错: {e}")
    
    def run_deep_analysis(self):
        """运行深度分析"""
        try:
            print("🔬 开始Ford Focus深度逆向分析...")
            print("=" * 60)
            
            if not self.setup_and_navigate():
                return False
            
            # 1. 滚动并分析
            self.scroll_and_analyze()
            
            # 2. 专门寻找规格按钮
            self.find_specification_buttons()
            
            # 3. 分析页面结构
            self.analyze_page_structure()
            
            # 4. 保存结果
            self.save_results()
            
            print("\n🎉 深度分析完成！")
            return True
            
        except Exception as e:
            error_msg = f"深度分析失败: {e}"
            print(f"❌ {error_msg}")
            self.results["errors"].append(error_msg)
            return False
        
        finally:
            self.cleanup()

def main():
    """主函数"""
    analyzer = FocusDeepAnalyzer()
    success = analyzer.run_deep_analysis()
    
    if success:
        print("\n📊 深度分析结果摘要:")
        print(f"  🚗 车型相关元素: {len(analyzer.results['models_detailed'])} 个")
        print(f"  🔘 交互按钮: {len(analyzer.results['interactive_elements'])} 个")
        print(f"  📋 规格按钮: {len(analyzer.results['specification_buttons'])} 个")
        print(f"  ❌ 错误数量: {len(analyzer.results['errors'])}")
        
        # 显示找到的规格按钮详情
        if analyzer.results['specification_buttons']:
            print("\n🔍 找到的规格相关按钮:")
            for button in analyzer.results['specification_buttons'][:5]:
                print(f"    - {button['search_text']}: {button['actual_text'][:50]}...")
        
        # 显示车型信息
        if analyzer.results['models_detailed']:
            print("\n🚗 找到的车型信息:")
            unique_texts = set()
            for model in analyzer.results['models_detailed']:
                text = model['text'][:80]
                if text not in unique_texts:
                    unique_texts.add(text)
                    print(f"    - {text}...")
    
    else:
        print("❌ 深度分析失败")

if __name__ == "__main__":
    main()
